"use client"

import { useState, useEffect } from "react"
import { Link } from "react-router-dom"
import "./Navbar.css"
import React from "react"

const Navbar = () => {
  const [userInfo, setUserInfo] = useState(null)
  const [isDropdownOpen, setIsDropdownOpen] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")
  const [searchTerm, setSearchTerm] = useState('');

  const handleSearchChange = (e) => {
      setSearchTerm(e.target.value);
  };

  useEffect(() => {
    const loadUserInfo = () => {
      try {
        const userId = localStorage.getItem("userId")
        const token = localStorage.getItem("token")

        if (userId) {
          setUserInfo({
            user_id: userId,
            token: token,
          })
          fetchUserAvatar()
        }
      } catch (error) {
        console.error("读取用户信息失败:", error)
      }
    }

    loadUserInfo()
  }, [])

  const handleLogout = () => {
    try {
      // 清除localStorage中的用户信息
      localStorage.removeItem("userId")
      localStorage.removeItem("avatarUrl")
      localStorage.removeItem("token")
      localStorage.removeItem("role")

      setUserInfo(null)
      setIsDropdownOpen(false)

      // 可以添加重定向到登录页面的逻辑
      window.location.href = "/auth"
    } catch (error) {
      console.error("登出失败:", error)
    }
  }

  const getAuthHeaders = () => {
    const token = localStorage.getItem("token")
    const userId = localStorage.getItem("userId")

    if (!token || !userId) {
      console.error("用户未登录")
      return null
    }

    return {
      Authorization: `Bearer ${token}`,
    }
  }

  // 获取用户头像
  const fetchUserAvatar = async () => {
    let avatarUrl = "/default_avatar.jpg";
    
    try {
      const userId = localStorage.getItem("userId");
      if (!userId) throw new Error("用户ID不存在");

      const response = await fetch(`/user/get-avatar?userId=${userId}`, {
        method: "GET",
        headers: getAuthHeaders(),
      });

      if (!response.ok) throw new Error(`获取头像失败: ${response.status}`);

      const data = await response.json();
      
      if (data.code === 0 && data.result) {
        avatarUrl = data.msg;

        if (avatarUrl) {
          if (avatarUrl.startsWith("data:image/")) {
            // Base64 with prefix
          } else if (avatarUrl.length > 1000) {
            avatarUrl = `data:image/jpeg;base64,${avatarUrl}`;
          } else if (!avatarUrl.startsWith("/") && !avatarUrl.startsWith("http")) {
            avatarUrl = `/${avatarUrl}`;
          }
        }
      }
    } catch (error) {
      console.error("获取头像错误:", error);
    }

    localStorage.setItem("avatarUrl", avatarUrl);
    return avatarUrl;
  };

  const handleClickOutside = (e) => {
    if (!e.target.closest(".user-profile-container")) {
      setIsDropdownOpen(false)
    }
  }

  useEffect(() => {
    if (isDropdownOpen) {
      document.addEventListener("click", handleClickOutside)
      return () => {
        document.removeEventListener("click", handleClickOutside)
      }
    }
  }, [isDropdownOpen])

  // SVG 图标组件
  const ChevronDownIcon = () => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polyline points="6,9 12,15 18,9"></polyline>
    </svg>
  )

  const UserIcon = () => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
      <circle cx="12" cy="7" r="4"></circle>
    </svg>
  )

  const LogOutIcon = () => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
      <polyline points="16,17 21,12 16,7"></polyline>
      <line x1="21" y1="12" x2="9" y2="12"></line>
    </svg>
  )

  return (
    <>
      <nav className="navbar">
        <div className="navbar-left">
          <Link to="/" className="navbar-item">
            首页
          </Link>
          <Link to="/promotions" className="navbar-item">
            促销
          </Link>
        </div>

        <div className="navbar-center">
          <div className="navbar-search-container">
              <input
                  type="text"
                  placeholder="输入搜索关键词"
                  className="search-bar"
                  value={searchTerm}
                  onChange={handleSearchChange}
              />
              <Link
                  to={`/search?q=${encodeURIComponent(searchTerm)}`}
                  className="navbar-item search-link"
              >
                  搜索
              </Link>
          </div>
        </div>

        <div className="navbar-right">
          <Link to="/shop" className="navbar-item">
            商城
          </Link>
          <Link to="/upload" className="navbar-item">
            上传
          </Link>
          <div className="navbar-userId">user_id:{localStorage.getItem("userId")}</div>
          {userInfo ? (
            <div className="user-profile-container">
              <button className="user-profile-button" onClick={() => setIsDropdownOpen(!isDropdownOpen)}>
                <img
                  src={localStorage.getItem("avatarUrl") || "/default_avatar.jpg"}
                  alt="用户头像"
                  className="avatar"
                  onError={(e) => {
                    // 头像加载失败时显示默认头像
                    e.currentTarget.src = "/default_avatar.jpg";
                  }}
                />
                <span className={`dropdown-icon ${isDropdownOpen ? "rotated" : ""}`}>
                  <ChevronDownIcon />
                </span>
              </button>

              {isDropdownOpen && (
                <div className="user-dropdown">
                  <Link to="/profile" className="dropdown-item">
                    <UserIcon />
                    个人资料
                  </Link>
                  <button onClick={handleLogout} className="dropdown-item logout-item">
                    <LogOutIcon />
                    登出
                  </button>
                </div>
              )}
            </div>
          ) : (
            <div className="auth-buttons">
              <Link to="/auth" className="navbar-item">
                登录
              </Link>
            </div>
          )}
        </div>
      </nav>
    </>
  )
}

export default Navbar
